from flask import Blueprint, jsonify, make_response, request
from flask_restful import Resource, Api, reqparse
from models.model import *

student_bp = Blueprint('student_bp', __name__, url_prefix='/')

api = Api(student_bp)




class Student_login(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('phone')
        req.add_argument('password')
        args = req.parse_args()

        student = Student.query.filter(Student.phone == args['phone'] and Student.password == args['password']).one()
        print(student)
        if student.id:
            resp = make_response("学生id 登录状态模拟")
            resp.set_cookie("student_id", str(student.id), max_age=36000)
            return resp
        return jsonify({
            'code':400
        })

class Student2teacherView(Resource):
    def put(self):
        req = reqparse.RequestParser()
        req.add_argument('teacher_id')
        args = req.parse_args()
        teacher_id = args['teacher_id']
        student_id = request.cookies.get("student_id")
        if not student_id:
            return jsonify({
                'code':403,
                'msg':'请登录'
            })
        teacher = Teacher.query.filter(Teacher.id == teacher_id).one()
        student = Student.query.filter(Student.id == student_id).one()
        if teacher.students:
            return jsonify({
                'code':400,
                'msg':'已经关注啦'
            })

        teacher.students.append(student)
        teacher.attention_num += 1
        db.session.commit()
        return jsonify({
            'code':200,
            'msg':'关注成功'
        })

api.add_resource(Student_login, 'student_login')
api.add_resource(Student2teacherView,'fllow_to_teacher')
